package com.eagle.view.fragment.call;

import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.opengl.GLSurfaceView;
import android.os.Handler;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eagle.R;
import com.eagle.support.common.CameraDataCallback;
import com.eagle.support.helper.CallHelper;
import com.eagle.support.utils.Utility;
import com.eagle.support.utils.Utils;
import com.eagle.support.utils.YuvRender;
import com.eagle.view.activity.VideoCallActivity;
import com.eagle.view.fragment.live.BaseFragment;
import com.eagle.view.widget.CameraTextureView;
import com.kinstalk.voip.jni.NVDataRender;
import com.kinstalk.voip.sdk.EngineSdkVideoPixelFormat;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.animation.PropertyValuesHolder;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

/**
 * Created by Administrator on 2017/1/16.
 */
@EFragment(R.layout.fragment_call)
public class FragmentCall extends BaseFragment implements CameraDataCallback {

    @ViewById(R.id.layout_video_remote)
    protected RelativeLayout mLayoutRemote;

    @ViewById(R.id.tv_video_live)
    protected CameraTextureView mCameraTextureView;

    @ViewById(R.id.videoSurfaceViewRemoteVideo)
    protected GLSurfaceView mSurfaceViewRemoteVideo;

    @ViewById(R.id.tv_download)
    protected TextView mTvDownload;

    @ViewById(R.id.tv_upload)
    protected TextView mTvUpload;

    @ViewById(R.id.btn_mute)
    protected ImageView mIvMute;

    private boolean mSwitchCamera;

    private int mPhoneOrientation = 3;

    private YuvRender mRemoteRender;

    private NVDataRender mRemoteDataRender = new NVDataRender();

    private CallHelper mCallHelper;

    private VideoCallActivity mActivity;

    @AfterViews
    void initView() {
        mActivity = (VideoCallActivity) getActivity();
        mCallHelper = mActivity.getCallHelper();
        mCameraTextureView.setDataCallback(FragmentCall.this);
        mCameraTextureView.setPreviewAreaSize(Utils.dip2px(90), Utils.dip2px(120));

        this.mRemoteRender = new YuvRender();
        this.mRemoteRender.setDataRender(mRemoteDataRender);
        mSurfaceViewRemoteVideo.setEGLContextClientVersion(2);
        mSurfaceViewRemoteVideo.setRenderer(mRemoteRender);
        mSurfaceViewRemoteVideo.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            handlerPreviewAnimator();
        }
    }

    private void handlerPreviewAnimator() {
        PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0.0f, 1.0f);
        PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 0.0f, 1.0f);
        PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 0.0f, 1.0f);
        PropertyValuesHolder translationX = PropertyValuesHolder.ofFloat("translationX", Utils.dip2px(142), 0);
        ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(mLayoutRemote, alpha, scaleX, scaleY, translationX);
        animator.setInterpolator(new OvershootInterpolator());
        animator.setDuration(300).start();
    }

    @Override
    public void onCameraData(byte[] data, android.hardware.Camera camera) {
        Camera.Size size = camera.getParameters().getPreviewSize();
        if (mCallHelper.getLoader().getCurrentCallInfo() != null && !isHidden()) {
            // 如果是前置摄像头， 需要将图像上下翻转
            int orientation = mPhoneOrientation;
            if (mCameraTextureView.getCameraId() == Camera.CameraInfo.CAMERA_FACING_FRONT && orientation % 2 == 1) {
                orientation = (orientation + 2) % 4;
            }
            mCallHelper.getLoader().getCurrentCallInfo().sendDataOnMainVideoChannel(EngineSdkVideoPixelFormat.ES_PIXEL_FORMAT_NV21, size.width, size.height, (char) orientation, data);
        }
    }

    public void onMainVideoDataInCall(long pointer, int width, int height, char rotation) {
        if (mRemoteDataRender != null && mRemoteRender != null && mSurfaceViewRemoteVideo != null) {
            mRemoteDataRender.CopytoRenderBuffer(pointer, width, height);
            if (!mRemoteRender.IsSetuped())
                mRemoteRender.SetupRender(width, height);
            mRemoteRender.updateFrameInfo(width, height, rotation);
            mSurfaceViewRemoteVideo.requestRender();
        }
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        super.onSensorChanged(sensorEvent);
        switch (sensorEvent.sensor.getType()) {
            case Sensor.TYPE_ACCELEROMETER:
                int newOrientation = Utility.getDirection((int) sensorEvent.values[0], (int) sensorEvent.values[1], (int) sensorEvent.values[2]);
                if (mPhoneOrientation != newOrientation) {
                    mPhoneOrientation = newOrientation;
                }
                break;
            case Sensor.TYPE_PROXIMITY:
                // onProximityChanged(event);
                break;
            default:
                break;
        }
    }

    /**
     * 切换镜头
     */
    @Click(R.id.btn_switch)
    protected void onSwitch() {
        mCameraTextureView.changeCamera();
        mSwitchCamera = !mSwitchCamera;
        switchRotationAnimator(mLayoutRemote);
    }

    @Click(R.id.btn_mute)
    protected void onMute() {
        mIvMute.setImageResource(mCallHelper.isSoundOff() ? R.mipmap.ic_mute_white : R.mipmap.ic_mute_blue);
        mCallHelper.getLoader().getCurrentCallInfo().setTransmitingAudioMute(!mCallHelper.isSoundOff());
    }

    /**
     * 弹出退出通话
     */
    @Click(R.id.btn_hang_up)
    protected void onHangup() {
        mActivity.popQuitLiveDialog();
    }

    public void switchRotationAnimator(View view) {
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "rotationY", 0.0F, 180.0F);
        objectAnimator.setDuration(300).start();
    }

    /**
     * 流量监听
     */
    public void receiverSpeed(String rx, String tx) {
        mTvDownload.setText(rx);
        mTvUpload.setText(tx);
    }

    public void handlerFinish() {
        mCameraTextureView.destroyCamera();
        mRemoteDataRender.DrawFinish();
    }
}
